define(['./module'], function (services) {
  'use strict';
  services.factory('Garment', function () {    var ViewLine;
    ViewLine = (function() {
      function ViewLine(product1) {
        this.product = product1;
        this.pivots = {};
        this.setProduct(this.product);
      }

      ViewLine.prototype.setProduct = function(product) {
        var color, i, len, ref, results, size;
        this.product = product != null ? product : {
          sizes: [],
          colors: []
        };
        this.sizes = this.product.sizes;
        this.colors = this.product.colors;
        ref = this.colors;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          color = ref[i];
          results.push((function() {
            var base, j, len1, name, ref1, results1;
            ref1 = this.sizes;
            results1 = [];
            for (j = 0, len1 = ref1.length; j < len1; j++) {
              size = ref1[j];
              if ((base = this.pivots)[name = color.id] == null) {
                base[name] = {};
              }
              results1.push(this.pivots[color.id][size.id] = 0);
            }
            return results1;
          }).call(this));
        }
        return results;
      };

      ViewLine.prototype.add_product_item = function(product_item, qty) {
        return this.add_color_size_qty(product_item.color.id, product_item.size.id, qty);
      };

      ViewLine.prototype.add_color_size_qty = function(color, size, qty) {
        return this.pivots[color][size] += qty;
      };

      ViewLine.prototype.getOrderLineJson = function() {
        var i, len, order_lines, product_item, qty, ref;
        order_lines = [];
        ref = this.product.product_items;
        for (i = 0, len = ref.length; i < len; i++) {
          product_item = ref[i];
          qty = this.pivots[product_item.color.id][product_item.size.id];
          if (qty > 0) {
            order_lines.push({
              product_item: product_item,
              qty: qty
            });
          }
        }
        return order_lines;
      };

      return ViewLine;

    })();
    return {
      viewLine: function(order) {
        var i, len, order_line, product, ref, viewLine, viewLines;
        viewLines = [];
        ref = order.order_lines;
        for (i = 0, len = ref.length; i < len; i++) {
          order_line = ref[i];
          product = order_line.product_item.product;
          viewLine = _.filter(viewLines, function(line) {
            return line.product.id === product.id;
          });
          if (viewLine.length <= 0) {
            viewLine = [new ViewLine(product)];
            viewLines.push(viewLine[0]);
          }
          viewLine[0].add_product_item(order_line.product_item, order_line.qty);
        }
        return viewLines;
      },
      newLine: function(product) {
        return new ViewLine(product);
      }
    };

  });
});
